package com.ruoyi.paip.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.GZIPInputStream;

public class HttpRequest {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 发起 HTTP 请求
    public static <T> T sendRequest(String urlString, String method, Map<String, String> headers,
                                    Map<String, String> params, String requestBody, Class<T> responseType) throws IOException {
        // 构建完整的 URL
        URL url = new URL(buildUrlWithParams(urlString, params));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method.toUpperCase());

        // 设置请求头
        setRequestHeaders(connection, headers);

        // 处理请求体（POST/PUT 请求）
        if (requestBody != null && !requestBody.isEmpty() && (method.equals("POST") || method.equals("PUT"))) {
            connection.setDoOutput(true);
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
        }

        // 获取响应体并处理压缩
        String response = handleResponse(connection);

        // 将响应体映射为指定的对象
        return objectMapper.readValue(response, responseType);
    }

    // 构建带查询参数的 URL
    @SneakyThrows
    private static String buildUrlWithParams(String urlString, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return urlString;
        }

        StringBuilder urlBuilder = new StringBuilder(urlString);
        urlBuilder.append(urlString.contains("?") ? "&" : "?");

        for (Map.Entry<String, String> param : params.entrySet()) {
            urlBuilder.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8.name()));
            urlBuilder.append("=");
            urlBuilder.append(URLEncoder.encode(param.getValue(), StandardCharsets.UTF_8.name()));
            urlBuilder.append("&");
        }

        // 移除最后一个 "&"
        return urlBuilder.substring(0, urlBuilder.length() - 1);
    }

    // 设置请求头
    private static void setRequestHeaders(HttpURLConnection connection, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                connection.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        // 默认的请求头
        connection.setRequestProperty("accept-encoding", "gzip, deflate, br");
    }

    // 处理响应体（包括解压缩 gzip 响应）
    private static String handleResponse(HttpURLConnection connection) throws IOException {
        // 获取响应代码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        InputStream inputStream;
        if ("gzip".equals(connection.getContentEncoding())) {
            inputStream = new GZIPInputStream(connection.getInputStream());
        } else {
            inputStream = connection.getInputStream();
        }

        // 读取响应数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder responseBody = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            responseBody.append(line);
        }

        return responseBody.toString();
    }

    // 测试方法
       public static void main(String[] args) throws IOException {
        String url = "https://api.m.jd.com/api";

        // 请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("x-referer-page", "/pages/index/index");
        headers.put("xweb_xhr", "1");
        headers.put("x-rp-client", "mini_2.0.0");
        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c11)XWEB/11581");
        headers.put("x-referer-package", "wx4987f0b3b115aae2");
        headers.put("accept", "*/*");
        headers.put("sec-fetch-site", "cross-site");
        headers.put("sec-fetch-mode", "cors");
        headers.put("sec-fetch-dest", "empty");
        headers.put("referer", "https://servicewechat.com/wx4987f0b3b115aae2/127/page-frame.html");
        headers.put("accept-encoding", "gzip, deflate, br");
        headers.put("accept-language", "zh-CN,zh;q=0.9");
        headers.put("cookie", "guid=5456f82547acd2a26dab66817ec201db4a9f98a3ecb04099d6c93a03e9165644; pt_pin=jd_66b89567df5ab; pt_key=AAJneSMWADDGXTuS9Ht2QLrdi1zcTHAU167PY_bLMQnd0laL5KKBQbw1F99g0IrbBVCucyavLX0; pt_token=; __jda=1.17359920210391667687448.1735992021039.1736233284.1736237242.5");

        // 请求参数
        Map<String, String> params = new HashMap<>();
        params.put("functionId", "pp.own.channel.biz.index.floor");
        params.put("appid", "paipai_wx");
        params.put("client", "m");
        params.put("ext", "%7B%22referer%22%3A%22wx4987f0b3b115aae2%2F4.4.1%2Fpages%2Findex%2Findex%22%7D");
        params.put("t", "1736238045618");
        params.put("h5st", "20250107162045619%3Byyqe8vlh1ezzuee2%3Bd9bf4%3Btk03ac7df1c3f18pMyszKzMrMTVLesls4UHwq6i74xMlReQ2xz9b2XsPj4YE6KDsbATOXOvJ7wAW0BZ_bEQiu0Jj88Yt%3Bc58b258c19af1e6f2e1a50f69e7d3e28%3B4.9%3B1736238045619%3Bq3EpJjYSGWENxWVfD6FOzXVPyGEjLDIj7SFjLrJp-jZf9HIg3T0UzelNJrJdJTEjLrJp-jJX9CUZb25R4bFbJrJdJ31QHyVT5ipjLD7N%3B49318bef48b5ae775e7c475e12c736b1");
        params.put("uuid", "17359920210391667687448");
        params.put("eid", "93A92CCD48893AA941C77D3754ADD7A99A97F22E");
        params.put("body", "%7B%22channel%22%3A2%7D");

        // 请求体（用于 POST 请求）
        String requestBody = "{\"channel\": 2}";

        // 调用请求方法并获取响应体（指定返回类型为 Map）
        Map<String, Object> response = sendRequest(url, "GET", headers, params, null, Map.class);
        System.out.println(response);
    }
}
